<template>
  <div class="thought-process-container">
    <!-- 简洁的标题栏 -->
    <div class="thought-header" @click="toggleExpanded">
      <div class="header-left">
        <div class="step-indicator">
          <span class="current-step">{{ currentStepNumber }}</span>
          <span class="step-divider">/</span>
          <span class="total-steps">{{ maxSteps }}</span>
        </div>
        <span class="header-title">思考过程</span>
      </div>
      <div class="header-right">
        <span class="step-status" :class="status">{{ getStepStatusText(status) }}</span>
        <div class="expand-icon" :class="{ expanded: isExpanded }">
          <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
            <path d="M4.646 6.646a.5.5 0 0 1 .708 0L8 9.293l2.646-2.647a.5.5 0 0 1 .708.708l-3 3a.5.5 0 0 1-.708 0l-3-3a.5.5 0 0 1 0-.708z"/>
          </svg>
        </div>
      </div>
    </div>

    <!-- 步骤内容区域 -->
    <div class="steps-content" v-show="isExpanded">
      <!-- 当前步骤详情 -->
      <div v-if="currentStep" class="current-step-detail">
        <!-- 步骤标题和状态 -->
        <div class="step-title-row">
          <div class="step-number-badge">{{ currentStep.number }}</div>
          <div class="step-title-content">
            <h3 class="step-title">{{ currentStep.title || '正在思考...' }}</h3>
            <p class="step-description">{{ currentStep.description }}</p>
          </div>
          <div class="step-status-indicator" :class="currentStep.status">
            <div class="status-dot"></div>
            <span>{{ getStepStatusText(currentStep.status) }}</span>
          </div>
        </div>

        <!-- 思考内容区域 -->
        <div v-if="currentStep.thinking" class="content-section">
          <div class="content-header">
            <div class="content-icon thinking">💭</div>
            <h4 class="content-title">思考</h4>
          </div>
          <div class="content-body thinking-content">
            {{ currentStep.thinking }}
          </div>
        </div>

        <!-- 工具选择区域 -->
        <div v-if="currentStep.toolSelection" class="content-section">
          <div class="content-header">
            <div class="content-icon tool">🔧</div>
            <h4 class="content-title">工具选择</h4>
          </div>
          <div class="content-body tool-content">
            <div class="tool-item">
              <div class="tool-info">
                <span class="tool-name">{{ currentStep.toolSelection.name }}</span>
                <span class="tool-action">{{ currentStep.toolSelection.action }}</span>
              </div>
              <div class="tool-params">
                {{ currentStep.toolSelection.params }}
              </div>
            </div>
          </div>
        </div>

        <!-- 结果区域 -->
        <div v-if="currentStep.result" class="content-section">
          <div class="content-header">
            <div class="content-icon result">✅</div>
            <h4 class="content-title">结果</h4>
          </div>
          <div class="content-body result-content">
            {{ currentStep.result }}
          </div>
        </div>
      </div>

      <!-- 步骤历史列表 -->
      <div v-if="processedSteps.length > 1" class="steps-history">
        <h4 class="history-title">已完成步骤</h4>
        <div class="history-list">
          <div
            v-for="(step, index) in processedSteps.slice(0, -1)"
            :key="index"
            class="history-item"
            @click="selectStep(index)"
            :class="{ active: selectedIndex === index }"
          >
            <div class="history-step-number">{{ step.number }}</div>
            <div class="history-content">
              <div class="history-title-text">{{ step.title || `步骤 ${step.number}` }}</div>
              <div class="history-description">{{ step.description || step.typeText }}</div>
            </div>
            <div class="history-status">
              <div class="history-status-dot" :class="step.status"></div>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="processedSteps.length === 0" class="empty-state">
        <div class="empty-icon">🤔</div>
        <div class="empty-text">AI 正在思考中...</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'

// Props
const props = defineProps({
  steps: {
    type: Array,
    default: () => []
  },
  status: {
    type: String,
    default: 'idle' // idle, thinking, acting, completed, error
  },
  initiallyExpanded: {
    type: Boolean,
    default: true
  },
  currentStepNumber: {
    type: Number,
    default: 1
  },
  maxSteps: {
    type: Number,
    default: 5
  }
})

// 响应式数据
const isExpanded = ref(props.initiallyExpanded)
const selectedIndex = ref(-1)

// 计算属性
const processedSteps = computed(() => {
  return props.steps.map((step, index) => {
    return {
      ...step,
      number: index + 1,
      timestamp: step.timestamp || Date.now(),
      status: step.status || 'thinking',
      title: generateStepTitle(step),
      description: generateStepDescription(step),
      thinking: extractThinkingContent(step.content || ''),
      toolSelection: extractToolSelection(step.content || ''),
      result: extractResult(step.content || ''),
      error: extractError(step.content || '')
    }
  })
})

const currentStep = computed(() => {
  if (processedSteps.value.length === 0) return null
  return selectedIndex.value >= 0
    ? processedSteps.value[selectedIndex.value]
    : processedSteps.value[processedSteps.value.length - 1]
})

// 方法
const toggleExpanded = () => {
  isExpanded.value = !isExpanded.value
}

const selectStep = (index) => {
  selectedIndex.value = selectedIndex.value === index ? -1 : index
}

const getStepStatusText = (status) => {
  const statusMap = {
    idle: '准备中',
    thinking: '思考中',
    acting: '执行中',
    completed: '已完成',
    error: '出错了'
  }
  return statusMap[status] || '进行中'
}

const generateStepTitle = (step) => {
  const content = step.content || ''

  if (content.includes('分析') || content.includes('理解')) {
    return '分析问题'
  } else if (content.includes('工具') || content.includes('选择')) {
    return '选择工具'
  } else if (content.includes('执行') || content.includes('调用')) {
    return '执行操作'
  } else if (content.includes('总结') || content.includes('完成')) {
    return '总结结果'
  }

  return `步骤 ${step.number || 1}`
}

const generateStepDescription = (step) => {
  const content = step.content || ''

  if (content.includes('用户问题') || content.includes('理解用户')) {
    return '理解用户的需求和问题'
  } else if (content.includes('搜索') || content.includes('查询')) {
    return '搜索相关信息'
  } else if (content.includes('分析') || content.includes('评估')) {
    return '分析收集到的信息'
  } else if (content.includes('总结') || content.includes('回答')) {
    return '总结并给出回答'
  }

  return getStepTypeText(step.type)
}

const getStepTypeText = (type) => {
  const typeMap = {
    think: '思考分析',
    act: '执行操作',
    tool_call: '工具调用',
    result: '获得结果',
    error: '出现错误'
  }
  return typeMap[type] || '处理中'
}

const extractThinkingContent = (content) => {
  // 提取思考标签内的内容
  const thinkingMatch = content.match(/<思考>([\s\S]*?)<\/思考>/)
  if (thinkingMatch) {
    return thinkingMatch[1].trim()
  }

  // 提取一般性思考内容
  const lines = content.split('\n').filter(line =>
    !line.includes('工具名称：') &&
    !line.includes('返回的结果：') &&
    !line.includes('Step') &&
    !line.includes('Terminated') &&
    line.trim()
  )

  return lines.length > 0 ? lines.join('\n').trim() : null
}

const extractToolSelection = (content) => {
  const toolCallRegex = /工具名称：([^\n，]+)，参数：([^\n]+)/g
  const match = toolCallRegex.exec(content)

  if (match) {
    return {
      name: match[1].trim(),
      action: '调用工具',
      params: match[2].trim()
    }
  }

  return null
}

const extractResult = (content) => {
  const resultMatch = content.match(/工具 ([^ ]+) 返回的结果：([\s\S]*?)(?=\n工具|\nStep|$)/)
  return resultMatch ? resultMatch[2].trim() : null
}

const extractError = (content) => {
  const errorMatch = content.match(/错误[:：]\s*([^\n]+)/i)
  return errorMatch ? errorMatch[1].trim() : null
}

// 监听步骤变化
watch(() => props.steps, (newSteps) => {
  if (newSteps.length > 0 && !isExpanded.value) {
    isExpanded.value = true
  }
  // 自动选择最新步骤
  selectedIndex.value = -1
}, { deep: true })
</script>

<style scoped>
/* 主容器 */
.thought-process-container {
  background: #ffffff;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  margin: 16px 0;
  overflow: hidden;
  box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
}

/* 标题栏 */
.thought-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f8fafc;
  border-bottom: 1px solid #e5e7eb;
  cursor: pointer;
  user-select: none;
  transition: background-color 0.2s ease;
}

.thought-header:hover {
  background: #f1f5f9;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.step-indicator {
  display: flex;
  align-items: center;
  gap: 4px;
  font-family: 'SF Mono', 'Monaco', 'Inconsolata', 'Roboto Mono', monospace;
  font-size: 14px;
  font-weight: 600;
  color: #6b7280;
}

.current-step {
  color: #1f2937;
  font-size: 16px;
}

.step-divider {
  color: #9ca3af;
  font-size: 14px;
}

.total-steps {
  color: #9ca3af;
  font-size: 14px;
}

.header-title {
  font-size: 14px;
  font-weight: 500;
  color: #374151;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.step-status {
  font-size: 12px;
  font-weight: 500;
  color: #6b7280;
  padding: 4px 8px;
  border-radius: 4px;
  background: #f3f4f6;
}

.step-status.thinking {
  color: #d97706;
  background: #fef3c7;
}

.step-status.acting {
  color: #0891b2;
  background: #ecfeff;
}

.step-status.completed {
  color: #059669;
  background: #d1fae5;
}

.step-status.error {
  color: #dc2626;
  background: #fee2e2;
}

.expand-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  color: #6b7280;
  transition: transform 0.2s ease;
}

.expand-icon.expanded {
  transform: rotate(180deg);
}

/* 步骤内容区域 */
.steps-content {
  background: #ffffff;
}

/* 当前步骤详情 */
.current-step-detail {
  padding: 20px;
  border-bottom: 1px solid #f3f4f6;
}

.step-title-row {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  margin-bottom: 20px;
}

.step-number-badge {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  background: #3b82f6;
  color: white;
  border-radius: 50%;
  font-size: 14px;
  font-weight: 600;
  flex-shrink: 0;
}

.step-title-content {
  flex: 1;
}

.step-title {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.step-description {
  margin: 0;
  font-size: 14px;
  color: #6b7280;
  line-height: 1.5;
}

.step-status-indicator {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  font-weight: 500;
}

.status-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: #9ca3af;
}

.step-status-indicator.thinking .status-dot {
  background: #f59e0b;
  animation: pulse 2s infinite;
}

.step-status-indicator.thinking {
  color: #92400e;
}

.step-status-indicator.acting .status-dot {
  background: #3b82f6;
}

.step-status-indicator.acting {
  color: #1e3a8a;
}

.step-status-indicator.completed .status-dot {
  background: #10b981;
}

.step-status-indicator.completed {
  color: #064e3b;
}

.step-status-indicator.error .status-dot {
  background: #ef4444;
}

.step-status-indicator.error {
  color: #991b1b;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

/* 内容区块 */
.content-section {
  margin-bottom: 16px;
}

.content-section:last-child {
  margin-bottom: 0;
}

.content-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.content-icon {
  font-size: 16px;
}

.content-icon.thinking {
  color: #8b5cf6;
}

.content-icon.tool {
  color: #3b82f6;
}

.content-icon.result {
  color: #10b981;
}

.content-title {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #374151;
}

.content-body {
  margin-left: 24px;
  font-size: 14px;
  line-height: 1.5;
  color: #4b5563;
}

.thinking-content {
  background: #faf5ff;
  border-left: 3px solid #8b5cf6;
  padding: 12px 16px;
  border-radius: 0 6px 6px 0;
}

.tool-content {
  background: #eff6ff;
  border-left: 3px solid #3b82f6;
  padding: 12px 16px;
  border-radius: 0 6px 6px 0;
}

.tool-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.tool-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.tool-name {
  font-weight: 600;
  color: #1e3a8a;
}

.tool-action {
  color: #6b7280;
  font-size: 12px;
}

.tool-params {
  font-family: 'SF Mono', 'Monaco', 'Inconsolata', 'Roboto Mono', monospace;
  font-size: 12px;
  color: #4b5563;
  background: #f1f5f9;
  padding: 8px 12px;
  border-radius: 4px;
}

.result-content {
  background: #f0fdf4;
  border-left: 3px solid #10b981;
  padding: 12px 16px;
  border-radius: 0 6px 6px 0;
}

/* 步骤历史 */
.steps-history {
  padding: 20px;
  background: #f9fafb;
  border-top: 1px solid #f3f4f6;
}

.history-title {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
  color: #374151;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.history-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.history-item:hover {
  border-color: #d1d5db;
  background: #fafbfc;
}

.history-item.active {
  border-color: #3b82f6;
  background: #eff6ff;
}

.history-step-number {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  background: #6b7280;
  color: white;
  border-radius: 50%;
  font-size: 12px;
  font-weight: 600;
  flex-shrink: 0;
}

.history-item.active .history-step-number {
  background: #3b82f6;
}

.history-content {
  flex: 1;
  min-width: 0;
}

.history-title-text {
  font-size: 14px;
  font-weight: 500;
  color: #1f2937;
  margin-bottom: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.history-description {
  font-size: 12px;
  color: #6b7280;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.history-status {
  flex-shrink: 0;
}

.history-status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #9ca3af;
}

.history-status-dot.completed {
  background: #10b981;
}

.history-status-dot.error {
  background: #ef4444;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #6b7280;
}

.empty-icon {
  font-size: 32px;
  margin-bottom: 8px;
  opacity: 0.6;
}

.empty-text {
  font-size: 14px;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .thought-header {
    padding: 10px 12px;
  }

  .step-title-row {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }

  .current-step-detail {
    padding: 16px;
  }

  .steps-history {
    padding: 16px;
  }

  .content-body {
    margin-left: 20px;
  }

  .history-item {
    padding: 10px;
  }
}
</style>